using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SmartTracking.API.Read.Application.Commands.Ewe_Files;
using SmartTracking.API.Read.DTO;
using SmartTracking.Domain.HQX;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace SmartTracking.API.Read.Application.CommandHandlers.Ewe_Files
{
    /// <summary>
    /// 母羊档案下拉框菜单命令处理器
    /// </summary>
    public class GetEweFileMenuCommandHandler : IRequestHandler<GetEweFileMenuCommand, ApiResult<List<ResMenuitemOutput>>>
    {
        private readonly IBaseRepository<EweFile> _eweRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetEweFileMenuCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="eweRepository">母羊档案仓储</param>
        /// <param name="mapper">对象映射器</param>
        /// <param name="logger">日志记录器</param>
        public GetEweFileMenuCommandHandler(
            IBaseRepository<EweFile> eweRepository,
            IMapper mapper,
            ILogger<GetEweFileMenuCommandHandler> logger)
        {
            _eweRepository = eweRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理母羊档案下拉框菜单查询命令
        /// </summary>
        /// <param name="request">母羊档案下拉框菜单查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>下拉框菜单项列表</returns>
        public async Task<ApiResult<List<ResMenuitemOutput>>> Handle(GetEweFileMenuCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var entities = await _eweRepository.GetAll()
                    .Where(e => !e.IsDeleted)
                    .Select(e => new ResMenuitemOutput
                    {
                        value = e.EweId,
                        label = e.EarSignal
                    })
                    .ToListAsync(cancellationToken);

                _logger.LogInformation($"母羊档案下拉框菜单查询成功，共获取 {entities.Count} 条记录");
                return new ApiResult<List<ResMenuitemOutput>>
                {
                    Code = ApiEnum.查询成功,
                    Message = "母羊档案下拉框菜单查询成功",
                    data = entities
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"母羊档案下拉框菜单查询时发生系统异常: {ex.Message}");
                return new ApiResult<List<ResMenuitemOutput>>
                {
                    Code = ApiEnum.查询失败,
                    Message = "系统异常，请联系管理员",
                    data = null
                };
            }
        }
    }
}